#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using pii = pair<int, int>;
#define rep(i, a, b) for (int i = (a); i <= (b); i++)
#define per(i, a, b) for (int i = (a); i >= (b); i--)
#define endl '\n'
const int N = 1005;

int n, m;
int p[N][N];
int vis[N][N];
int dx[] = {-1, 0, 1, 0};
int dy[] = {0, 1, 0, -1};
void dfs(int x, int y, int val) {
  if (x < 1 || x > n || y < 1 || y > m) return;
  if (p[x][y] > val || vis[x][y]) return;
  vis[x][y] = 1;
  rep(i, 0, 3) {
    int xx = x + dx[i];
    int yy = y + dy[i];
    dfs(xx, yy, val);
  }
}
bool check(int x) {
  rep(i, 1, n) rep(j, 1, m) vis[i][j] = 0;
  dfs(1, 1, x);
  return vis[n][1];
}
int main() {
  ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
  cin >> n >> m;
  rep(i, 1, n) rep(j, 1, m) cin >> p[i][j];
  int l = 0, r = 1000;
  while (l <= r) {
    int mid = (l + r) >> 1;
    if (check(mid))
      r = mid - 1;
    else
      l = mid + 1;
  }
  cout << l;
  return 0;
}